package com.hulk.dryad.manage.framework.websocket.server.user;

import cn.hutool.core.util.StrUtil;
import com.hulk.dryad.manage.framework.websocket.server.cluster.RedisMessageConfiguration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * redis 实现
 *
 * @author hulk
 */
@Configuration(proxyBeanMethods = false)
@AutoConfigureAfter(RedisMessageConfiguration.class)
@ConditionalOnClass(RedisTemplate.class)
@ConditionalOnProperty(value = "websocket.server.userStore.name" , havingValue = "redis", matchIfMissing = true)
public class RedisWsUserStore implements IWsUserStore {

	private final SetOperations<String, Object> opsForSet;

	@Autowired
	public RedisWsUserStore(RedisTemplate<String, Object> redisTemplate) {
		this.opsForSet = redisTemplate.opsForSet();
	}

	@Override
	public List<String> listAll(String tenant) {
		List<String> list = new ArrayList<>();
		String  key = tenant+ StrUtil.COLON+ STORE_KEY;
		Set<Object> members = opsForSet.members(key);
		if (members != null && !members.isEmpty()) {
			members.forEach(member -> list.add((String) member));
		}
		return list;
	}

	@Override
	public boolean has(String userInfo) {
	    String  key = pickTenant(userInfo)+ StrUtil.COLON+ STORE_KEY;
		return opsForSet.isMember(key, userInfo);
	}

	@Override
	public void put(String userInfo) {
		String  key = pickTenant(userInfo)+ StrUtil.COLON+ STORE_KEY;
		opsForSet.add(key, userInfo);
	}

	@Override
	public void remove(String userInfo) {
		String  key = pickTenant(userInfo)+ StrUtil.COLON+ STORE_KEY;
		opsForSet.remove(key, userInfo);
	}


}
